package com.opages.netty.demo;

import java.io.*;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

/**
 * @author daizhong.liu
 * @create 2021-12-02 10:17
 **/
public class FileChannelDemo {

    public void writeFile() throws IOException{
        FileOutputStream fos = new FileOutputStream(new File("d://fileChannel.txt"));
        FileChannel channel = fos.getChannel();
        ByteBuffer bbf = ByteBuffer.allocate(1024);
        bbf.put("这是FileChannel".getBytes());
        bbf.flip();
        channel.write(bbf);
        channel.close();
    }
    public void readFile() throws IOException {
        File file = new File("d://fileChannel.txt");
        FileInputStream fis = new FileInputStream(file);
        FileChannel fisChannel = fis.getChannel();
        ByteBuffer bbf = ByteBuffer.allocate((int)file.length());
        fisChannel.read(bbf);
        System.err.println(new String(bbf.array()));
    }

    public void fileCopy() throws IOException {
        FileInputStream fis = new FileInputStream(new File("d://fileChannel.txt"));
        FileChannel fileInputChannel = fis.getChannel();

        FileOutputStream fos = new FileOutputStream(new File("d://fileOutChannel.txt"));
        FileChannel fileOutputChannel = fos.getChannel();

        ByteBuffer buffer = ByteBuffer.allocate(10);
        while (true) {
            int read = fileInputChannel.read(buffer);
            if(read == -1) {
                break;
            }
            buffer.flip();
            fileOutputChannel.write(buffer);
            buffer.clear();
        }
        fileInputChannel.close();
        fileOutputChannel.close();
    }

    public void transferFromFile() throws IOException {
        FileInputStream fis = new FileInputStream(new File("d://fileChannel.txt"));
        FileChannel fileSrcChannel = fis.getChannel();
        FileOutputStream fos = new FileOutputStream(new File("d://fileTarChannel.txt"));
        FileChannel fileTargetChannel = fos.getChannel();

        fileTargetChannel.transferFrom(fileSrcChannel,0,fileSrcChannel.size());
    }

    public static void main(String[] args) throws IOException {
        FileChannelDemo fcd = new FileChannelDemo();
//        fcd.writeFile();
//        fcd.readFile();
//        fcd.fileCopy();
        fcd.transferFromFile();
    }
}
